package ute.mvc.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ute.mvc.dao.ClassDAO;
import ute.mvc.dao.TestAndQuizzDAO;
import ute.mvc.model.MyClass;
import ute.mvc.model.OpenCourse_Subject;
import ute.mvc.model.SubmittedTestAndQuizz;
import ute.mvc.model.TestAndQuizz;
import ute.mvc.model.TestAndQuizz_Student;
import ute.mvc.model.User;

@Service("testAndQuizzService")
public class TestAndQuizzServiceImpl implements TestAndQuizzService {

	@Autowired
	TestAndQuizzDAO testAndQuizzDAO;
	@Autowired
	ClassDAO classDAO;

	@Transactional
	public void addTestAndQuizz(TestAndQuizz testAndQuizz) {
		testAndQuizzDAO.addTestAndQuizz(testAndQuizz);
	}

	@Transactional
	public void updateTestAndQuizz(TestAndQuizz testAndQuizz) {
		testAndQuizzDAO.updateTestAndQuizz(testAndQuizz);

	}

	@Transactional
	public void deleteTestAndQuizz(TestAndQuizz testAndQuizz) {
		testAndQuizzDAO.deleteTestAndQuizz(testAndQuizz);
	}

	public TestAndQuizz getTestAndQuizz(String id) {
		// TODO Auto-generated method stub
		return testAndQuizzDAO.getTestAndQuizz(id);
	}

	public String getMaxIdInOpenCourseSubject(OpenCourse_Subject subject) {
		// TODO Auto-generated method stub
		return testAndQuizzDAO.getMaxIdInOpenCourseSubject(subject);
	}

	public List<TestAndQuizz> getTestBySubject(OpenCourse_Subject subject,
			User user) {
		// TODO Auto-generated method stub
		return testAndQuizzDAO.getTestBySubject(subject, user);
	}

	public List<MyClass> getClassByTestId(String testId) {
		// TODO Auto-generated method stub
		return testAndQuizzDAO.getClassByTestId(testId);
	}

	@Transactional
	public void updateClasses(String testId, String classes) {
		// TODO Auto-generated method stub
		String[] listClass = classes.substring(1).split(";");
		List<MyClass> lstAssignClass = new ArrayList<MyClass>();
		for (int i = 0; i < listClass.length; i++) {
			lstAssignClass.add(classDAO.getClassById(listClass[i]));
		}
		TestAndQuizz test = testAndQuizzDAO.getTestAndQuizz(testId);
		test.setListClass(lstAssignClass);
		testAndQuizzDAO.updateTestAndQuizz(test);
	}

	public TestAndQuizz_Student getTestAndQuizzByStudent(User student, String testId) {
		// TODO Auto-generated method stub
		List<TestAndQuizz_Student> lstStudentTest = new ArrayList<TestAndQuizz_Student>();
		lstStudentTest.addAll(student.getListSubmittedTest());
		
		for(TestAndQuizz_Student test: lstStudentTest){
			if(test.getTestAndQuizz().getTestAndQuizzID().equals(testId)){
				return test;
			}
		}
		return null;
	}
}
